<template>
  <div id="admin-manage" class="page-wrapper">
    <div class="selector-wrapper main-card wrapper">
      <div class="main-card">
        <el-form class="form" :inline="true" ref="form" :model="formData">
          <el-form-item label="商品名称" prop="goodsName">
            <el-input v-model.trim="formData.goodsName" placeholder="请输入"></el-input>
          </el-form-item>

          <el-form-item label="商品等级" prop="grade">
            <el-select v-model="formData.grade" placeholder="请选择">
              <el-option v-for="item in optionsGrade" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="商品分类" prop="goodsLxID">
            <el-select v-model="formData.goodsLxID" placeholder="请选择">
              <el-option v-for="item in options2" :key="item.id" :label="item.LXName" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <el-button type="primary" @click="handleSubmitClick" :loading="loading">获取数据</el-button>
      <el-button type="success" @click="addGoods">新增产品</el-button>
    </div>
    <div class="wrapper main-card">
      <el-table :data="pageData" style="width: 100%" :stripe="true">
        <el-table-column prop="goodsName" label="商品名称"></el-table-column>
        <el-table-column prop="details" label="商品详情"></el-table-column>
        <el-table-column label="图片">
          <template slot-scope="scope">
            <img :src="scope.row.image" alt="图片" class="image-preview" />
          </template>
        </el-table-column>
        <el-table-column prop="money" label="商品价格"></el-table-column>
        <!-- <el-table-column prop="goodsLxID" label="商品分类"></el-table-column> -->
        <el-table-column label="商品分类">
          <template slot-scope="scope">
            <span>{{ goodsLxLabel(scope.row.goodsLxID) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="inventory" label="商品库存"></el-table-column>
        <el-table-column prop="sales" label="商品销量"></el-table-column>
        <el-table-column label="商品等级">
          <template slot-scope="scope">
            <span>{{ gradeLabel(scope.row.grade) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <span>{{ scope.row.state === 1 ? '销售中' : '已下架' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button @click="handleAction(scope.row, 'toggle')" :type="scope.row.state === 1 ? 'danger' : 'success'">
              {{ scope.row.state === 1 ? '下架' : '上架' }}
            </el-button>
            <el-button @click="handleAction(scope.row, 'modify')" type="primary">修改</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </div>

    <el-dialog title="商品详情" :visible.sync="dialogVisible" width="800px" @close="resetForm">
      <el-tabs type="border-card">
        <el-form class="form" ref="form" :model="modifydata" :rules="rules">
          <div class="form-item-wrapper">
            <el-form-item label="商品名称" required prop="goodsName">
              <el-input v-model.trim="modifydata.goodsName"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" required prop="money">
              <el-input v-model.trim="modifydata.money" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="商品介绍" required prop="details">
              <el-input v-model.trim="modifydata.details" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="库存" required prop="inventory">
              <el-input v-model.trim="modifydata.inventory" placeholder="请输入"></el-input>
            </el-form-item>
          </div>
          <div class="form-item-wrapper">
            <el-form-item label="商品等级" required prop="grade">
              <el-select v-model="modifydata.grade" placeholder="请选择">
                <el-option v-for="item in optionsGrade" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="商品分类" required prop="goodsLxID">
              <el-select v-model="modifydata.goodsLxID" placeholder="请选择">
                <el-option v-for="item in options2" :key="item.id" :label="item.LXName" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="商品状态" required prop="state">
              <el-select v-model="modifydata.state" placeholder="请选择">
                <el-option label="销售中" :value="1"></el-option>
                <el-option label="已下架" :value="0"></el-option>
              </el-select>
            </el-form-item>
            
            <el-form-item label="商品图片" prop="signatureImage">
              <input type="file" @change="handleFileChange" />
              <img v-if="modifydata.signatureImageUrl" :src="modifydata.signatureImageUrl" class="image-preview" />
            </el-form-item>
          </div>
        </el-form>
      </el-tabs>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="uploadGoods">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { searchgoodsinfo, uploadgoodsinfo, changegoodsstate, chanhegoodsinfo, goodslx, getgrade } from '@/api/pcclinet';

export default {
  name: 'RoomInfo',
  data() {
    return {
      currentPage: 1,
      pageData: [],
      total: 0,
      pageSize: 10,
      dialogVisible: false,
      formData: {
        goodsName: '',
        grade: '',
        goodsLxID: ''
      },
      modifydata: {
        id: '',
        goodsName: '',
        details: '',
        money: '',
        grade: '',
        state: '',
        inventory: '',
        signatureImage: '',
        signatureImageUrl: ''
      },
      loading: false,
      rules: {
        goodsName: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        money: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        details: [{ required: true, message: '请输入商品详情', trigger: 'blur' }],
        grade: [{ required: true, message: '请选择商品等级', trigger: 'change' }],
        state: [{ required: true, message: '请选择商品状态', trigger: 'change' }],
        goodsLxID: [{ required: true, message: '请选择商品分类', trigger: 'change' }]
      },
      optionsGrade: [],
      options2: []
    };
  },
  methods: {
    goodslx() {
      this.options2 = [];
      goodslx().then((res) => {
        const goodlx = res.data.goodlx;
        goodlx.forEach(element => {
          this.options2.push({ id: element.id, LXName: element.LXName });
        });
      }).catch((err) => {});
    },
    getgrade() {
      this.optionsGrade = [];
      getgrade().then((res) => {
        const optionsGrade = res.data.goodslist;
        optionsGrade.forEach(element => {
          this.optionsGrade.push({ value: element.id, label: element.label });
        });
      });
    },
    queryByPage() {
      const start = (this.currentPage - 1) * this.pageSize;
      return this.tableData.slice(start, start + this.pageSize);
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.pageData = this.queryByPage();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.pageData = this.queryByPage();
    },
    handleSubmitClick() {
      this.loading = true;
      this.getGoodsData(this.formData);
    },
    handleAction(row, action) {
      if (action === 'toggle') {
        this.toggleGoodsState(row);
      } else if (action === 'modify') {
        this.modifydata = { ...row };
        this.modifydata.signatureImageUrl = row.image;
        this.dialogVisible = true;
      }
    },
    addGoods() {
      this.modifydata = {
        id: '',
        goodsName: '',
        details: '',
        money: '',
        grade: '',
        state: '',
        inventory: '',
        signatureImage: '',
        signatureImageUrl: ''
      };
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
    },
    resetForm() {
      this.$refs.form.resetFields();
    },
    uploadGoods() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const formData = new FormData();
          formData.append('id', this.modifydata.id);
          formData.append('goodsName', this.modifydata.goodsName);
          formData.append('details', this.modifydata.details);
          formData.append('money', this.modifydata.money);
          formData.append('grade', this.modifydata.grade);
          formData.append('state', this.modifydata.state);
          formData.append('inventory', this.modifydata.inventory);
          formData.append('goodsLxID', this.modifydata.goodsLxID);
          if (this.modifydata.signatureImage) {
            formData.append('signatureImage', this.modifydata.signatureImage);
          }

          const apiCall = this.modifydata.id ? chanhegoodsinfo(formData) : uploadgoodsinfo(formData);
          apiCall.then(res => {
            if (res.success) {
              this.dialogVisible = false;
              this.getGoodsData();
              this.$message.success(this.modifydata.id ? '商品修改成功' : '商品上传成功');
            } else {
              this.$message.error('操作失败: ' + res.message);
            }
          }).catch(error => {
            this.$message.error('操作失败，请重试');
            console.error('Error:', error);
          });
        } else {
          this.$message.error('请完整填写表单信息');
        }
      });
    },
    handleFileChange(event) {
      const file = event.target.files[0];
      const maxSize = 60 * 1024; // 60KB in bytes

      if (file) {
        if (file.size > maxSize) {
          this.$message.error('上传的文件大小不能超过60KB');
          return;
        }
        this.modifydata.signatureImage = file;
        this.modifydata.signatureImageUrl = URL.createObjectURL(file);
      }
    },
    getGoodsData(filters = {}) {
      searchgoodsinfo(filters).then(res => {
        if (res.success) {
          this.loading = false;
          this.tableData = res.data;
          this.total = res.data.length;
          this.pageData = this.queryByPage();
          console.log(this.pageData);
          
        }
      }).catch(error => {
        console.error('Error fetching goods data:', error);
      });
    },
    toggleGoodsState(row) {
      const data = {
        id: row.id,
        state: row.state === 1 ? 0 : 1
      };
      changegoodsstate(data).then(res => {
        if (res.success) {
          this.getGoodsData();
        } else {
          console.error('Error changing goods state:', res.message);
        }
      }).catch(error => {
        console.error('Error changing goods state:', error);
      });
    },
    goodsLxLabel(grade){
      // console.log(grade);
      // console.log(this.options2[0]);
      
      const gradeLabel = this.options2.find(item => item.id ==  grade);
      return gradeLabel ? gradeLabel.LXName : '';
    },
    gradeLabel(grade) {
      const gradeLabel = this.optionsGrade.find(item => item.value == grade);
      return gradeLabel ? gradeLabel.label : '';
    }
  },
  mounted() {
    this.goodslx();
    this.getGoodsData();
    this.getgrade();
  }
}
</script>

<style lang="scss" scoped>
.wrapper {
  margin: 40px 0;
}

.selector-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.form-item-wrapper {
  display: flex;
  justify-content: space-between;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.image-preview {
  max-width: 100px;
  max-height: 50px;
  margin-top: 10px;
}
</style>
